package com.easytouch.core.utils;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;

import com.easytouch.core.Configure;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static android.content.Context.ACTIVITY_SERVICE;
import static android.content.Context.ALARM_SERVICE;

/**
 * 系统工具类
 * Created by gulin on 2017/7/17.
 */

public class SystemTools {

    public static boolean isRoot = true;

    /**
     * 重启
     */
    public static void reboot() {
        if(isRoot) {
            Process su = null;
            OutputStream os = null;
            try {
                su = Runtime.getRuntime().exec("su");
                os = su.getOutputStream();
                os.write(("reboot\n").getBytes());
                os.write("exit\n".getBytes());
                os.flush();
                su.waitFor();
            } catch (Exception e) {
            } finally {
                try {
                    if (os != null)
                        os.close();
                    if (su != null) {
                        su.destroy();
                    }
                } catch (IOException e) {
                }
            }
        }
        else
        {
//            initSystemDoor();
//            if(mDoor != null)
//            {
//                try {
//                    mDoor.rebootSystem();
//                } catch (RemoteException e) {
//                    mLogger.e(e.toString());
//                }
//            }
        }
    }

    /**
     * 隐藏三个系统按键
     */
    public static void hideSystemBar() {
        if(isRoot && Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    Process su = null;
                    OutputStream os = null;
                    try {
                        su = Runtime.getRuntime().exec("su");
                        os = su.getOutputStream();
                        String cmd = "service call activity 42 s16 com.android.systemui\n";
                        os.write(cmd.getBytes());
                        String exit = "exit\n";
                        os.write(exit.getBytes());
                        su.waitFor();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {

                        try {
                            if (os != null)
                                os.close();

                            if (su != null) {
                                su.destroy();
                            }
                        } catch (IOException e) {
                        }
                    }
                }

            }.start();
        }
        else
        {
            //mLogger.i("hideSystemBar");
            Intent i = new Intent();
            i.setAction("com.easytouch.systembar");
            i.putExtra("status", "0");
            if(Configure.context != null)
                Configure.context.sendBroadcast(i);
        }
    }

    /**
     * 显示系统三个按键
     */
    public static void showSystemBar() {
        if(isRoot && Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    Process su = null;
                    OutputStream os = null;
                    try {
                        su = Runtime.getRuntime().exec("su");
                        os = su.getOutputStream();
                        String cmd = "am startservice -n com.android.systemui/.SystemUIService\n";
                        os.write(cmd.getBytes());
                        String exit = "exit\n";
                        os.write(exit.getBytes());
                        su.waitFor();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (os != null)
                                os.close();

                            if (su != null) {
                                su.destroy();
                            }
                        } catch (IOException e) {
                        }
                        System.exit(0);
                    }
                }
            }.start();
        }
        else
        {
            //mLogger.i("showSystemBar");
            Intent i = new Intent();
            i.setAction("com.easytouch.systembar");
            i.putExtra("status", "1");
            if(Configure.context != null)
                Configure.context.sendBroadcast(i);
        }
    }

    /**
     * 设置系统时间
     * @param time 要设置的时间
     */
    public static void setSystemTime(final String time) {
        if(isRoot) {
            Process su = null;
            OutputStream os = null;
            try {
                su = Runtime.getRuntime().exec("su");
                os = su.getOutputStream();
                os.write(("date -s " + time + "\n").getBytes());
                os.write("exit\n".getBytes());
                // os.write("clock -w\n".getBytes());
                os.flush();
                su.waitFor();
            } catch (Exception e) {
                //CrashHandler.getInstance().saveCrashInfo2File(e);
            } finally {

                try {
                    if (os != null)
                        os.close();

                    if (su != null) {
                        su.destroy();
                    }
                } catch (IOException e) {
                }
            }
        }
        else
        {
            //mLogger.i("setSystemTime");
            Intent intent = new Intent("com.sfexpress.setSystemTime");
            Date date;
            try
            {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd.HHmmss");
                date = sdf.parse(time);
            }
            catch (ParseException e)
            {
                //mLogger.e(e.toString());
                return;
            }
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            long when = c.getTimeInMillis();
            intent.putExtra("system_time", when);
            if(Configure.context != null)
                Configure.context.sendBroadcast(intent);
        }
    }

    /**
     * 设置重启时间
     */
    public static void setRebootTime(){
        String rebootTime = Configure.getConfigData(Configure.CONFIG_REBOOT_TIME);
        if(rebootTime == null || "".equals(rebootTime) || rebootTime.length() < 4)
            return;
        String[] timeArray = rebootTime.split(";");
        if(timeArray == null || timeArray.length < 1)
            return;
        long current = System.currentTimeMillis();
        //对时间进行排序，找到从现在开始的最近时间
        ArrayList<Long> timeList = new ArrayList<Long>();
        for (String time: timeArray) {
            if(time.length() != 4)
                continue;
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(current);
            try
            {
                calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.substring(0, 2)));
                calendar.set(Calendar.MINUTE, Integer.parseInt(time.substring(2, 4)));
                calendar.set(Calendar.SECOND, 0); //秒
            }
            catch (NumberFormatException e)
            {
                continue;
            }
            long alarmTime = calendar.getTimeInMillis();
            if(alarmTime < current)
            {
                calendar.add(Calendar.DATE, 1); //+1天
                alarmTime = calendar.getTimeInMillis();
            }
            timeList.add(alarmTime);
        }
        if(timeList.size() < 1)
            return;
        Collections.sort(timeList);

        if(Configure.context != null) {
            AlarmManager alarmManager = (AlarmManager) Configure.context.getSystemService(ALARM_SERVICE);
            Intent intent = new Intent("com.easytouch.REBOOT");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(Configure.context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, timeList.get(0), pendingIntent);
        }
    }

    /**
     * 1分钟后异步方式检查远程更新程序是否已经安装，如果已安装就运行远程更新程序
     */
    public static void checkAndStartRemoteUpdaterAsync()
    {
        //检测并启动远程更新
        new Thread()
        {
            @Override
            public void run()
            {
                super.run();
                String apkName = "com.easytouch.remoteupdater";
                try
                {
                    sleep(60 * 1000); //一分钟后开始检测
                }
                catch(InterruptedException e)
                {
                    e.printStackTrace();
                }
                if(Configure.context == null)
                {
                    return;
                }
                if(checkApkInstalled(Configure.context, apkName)) //先判断新版的远程升级，已安装的话就调起来
                {
                    if(!appIsRunning(Configure.context, apkName))
                    {
                        //启动APP
                        Intent intent = new Intent();
                        intent.setComponent(new ComponentName(apkName, apkName + ".activity.MainActivity"));
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        Configure.context.startActivity(intent);
                    }
                }
//                else //没有安装新版的远程升级，调起老版的
//                {
//                    apkName = "com.solarmindet.ass_autosolder";
//                    if(checkApkInstalled(Configure.context, apkName))
//                    {
//                        if(!appIsRunning(Configure.context, apkName))
//                        {
//                            //启动APP
//                            Intent intent = new Intent();
//                            intent.setComponent(new ComponentName(apkName, apkName + ".activity.MainActivity"));
//                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            Configure.context.startActivity(intent);
//                        }
//                    }
//                }
            }

        }.start();
    }

    /**
     * 检查特定APK是否安装
     *
     * @param context 上下文
     * @param packageName 包名
     * @return 是否安装
     */
    public static boolean checkApkInstalled(Context context, String packageName)
    {
        PackageManager pm = context.getPackageManager();
        if("".equals(packageName) || packageName == null)
            return false;
        try
        {
            pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            return true;
        }
        catch(PackageManager.NameNotFoundException e)
        {
            return false;
        }
    }

    /**
     * 判断app是否正在运行
     * @param ctx 上下文
     * @param packageName 包名
     * @return
     */
    public static boolean appIsRunning(Context ctx, String packageName)
    {
        ActivityManager am = (ActivityManager) ctx.getSystemService(ACTIVITY_SERVICE);

        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();

        if(runningAppProcesses!=null)
        {
            for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {

                if(runningAppProcessInfo.processName.startsWith(packageName))
                {
                    return true;
                }
            }
        }

        return false;
    }

    public static boolean isRoot()
    {
        //第一种判断方法
        try {
            File file = new File("/system/app/Superuser.apk");
            if (file.exists()) {
                return true;
            }
        }
        catch (Exception e) { }
        //mLogger.i("check root first way pass");
        //第二种判断方法
        final String kSuSearchPaths[]={"/system/bin/","/system/xbin/","/system/sbin/","/sbin/","/vendor/bin/"};
        try
        {
            for(int i = 0;i < kSuSearchPaths.length;i++)
            {
                File f = new File(kSuSearchPaths[i]+"su");
                if(f != null && f.exists())
                {
                    return true;
                }
            }
        }catch(Exception e)
        {}
        //mLogger.i("check root second way pass");
        //第三种判断方法
        String buildTags = android.os.Build.TAGS;
        if (buildTags != null && buildTags.contains("test-keys")) {
            return true;
        }
        //mLogger.i("check root third way pass");
        return false;
    }

    public static void initSystemDoor()
    {
        isRoot = isRoot();
        //if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
        if(isRoot)
        {
//            if(mDoor == null)
//            {
//                LSApplication.context.bindService(new Intent("com.zb.systemtools.Door"), mServiceConnection, Context.BIND_AUTO_CREATE);
//            }
        }
    }
}
